import Cookies from 'js-cookie'
import { getCustomerAll } from '@/api/customers'

const app = {
  state: {
    sidebar: {
      opened: !+Cookies.get('sidebarStatus'),
      withoutAnimation: false
    },
    customerid: null,
    customername: '',
    device: 'desktop'
  },
  mutations: {
    TOGGLE_SIDEBAR: state => {
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
      state.sidebar.withoutAnimation = false
    },
    CLOSE_SIDEBAR: (state, withoutAnimation) => {
      Cookies.set('sidebarStatus', 1)
      state.sidebar.opened = false
      state.sidebar.withoutAnimation = withoutAnimation
    },
    TOGGLE_DEVICE: (state, device) => {
      state.device = device
    },
    SET_CUSTOMERID: (state, customerid) => {
      state.customerid = customerid
    },
    SET_CUSTOMERNAME: (state, customername) => {
      state.customername = customername
    }
  },
  actions: {
    ToggleSideBar: ({ commit }) => {
      commit('TOGGLE_SIDEBAR')
    },
    CloseSideBar({
      commit
    }, {
      withoutAnimation
    }) {
      commit('CLOSE_SIDEBAR', withoutAnimation)
    },
    ToggleDevice({
      commit
    }, device) {
      commit('TOGGLE_DEVICE', device)
    },
    SetCustomerInfo({ commit }, info) {
      commit('SET_CUSTOMERID', info.customerid)
      commit('SET_CUSTOMERNAME', info.customername)
    },
    // 获取客户信息
    GetCustomerInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getCustomerAll().then(response => {
          if (response.data.length) {
            let customerid = null
            response.data.forEach(customer => {
              commit('SET_CUSTOMERID', customer.id)
              commit('SET_CUSTOMERNAME', customer.customerName)
              customerid = customer.id
            })
            resolve(customerid)
          } else {
            commit('SET_CUSTOMERID', null)
            commit('SET_CUSTOMERNAME', '')
            resolve(null)
          }
          reject(new Error('can not get customerinfo'))
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default app
